package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;

public class ServerThread implements Runnable{
    private Socket socket;
    public ServerThread(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        BufferedReader br=null;
        try {
            // 3、从socket通信管道中得到一个字节输入流。
            InputStream is = socket.getInputStream();
            // 4、把原始的字节输入流包装成高效的输入流
            InputStreamReader isr=new InputStreamReader(is);
            br=new BufferedReader(isr);
            // 5、使用数据输入流读取客户端发送过来的消息
            while(true){
                String s = br.readLine();
                if(s==null){//断开连接
                    Server.list.remove(socket);
                    break;
                }
                System.out.println(s);
                //遍历结合 拿到每一个socket
                for(Socket socket:Server.list){
                    BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    if(socket!=this.socket){
                        bw.write(s); //socket
                        bw.newLine();
                        bw.flush();
                    }

                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 6、释放资源
            try {
                if(br!=null)
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }
}
